package ru.aslanov.schedule.client;

import com.smartgwt.client.data.DSCallback;
import com.smartgwt.client.data.DSRequest;
import com.smartgwt.client.data.DSResponse;
import com.smartgwt.client.data.Record;
import ru.aslanov.schedule.client.ds.GoogleCalendarSyncDS;
import ru.aslanov.schedule.shared.SyncStatus;

import java.util.Date;

/**
 * Created by IntelliJ IDEA.
 * Created: Mar 4, 2010 1:33:38 PM
 *
 * @author Sergey Aslanov
 */
public class GCalendarSyncData {
    private String scheduleKey;

    private boolean hasSessionToken;
    private String authorizedByUser;
    private Date lastPublishDate;
    private String lastPublishErrors;
    private UpdateListener updateListener;
    private SyncStatus syncStatus;


    public GCalendarSyncData(String scheduleKey, UpdateListener updateListener) {
        this.scheduleKey = scheduleKey;
        this.updateListener = updateListener;

        refresh();
    }

    public void refresh() {
        GoogleCalendarSyncDS.getInstance(scheduleKey).fetchData(null, new DSCallback() {
            @Override
            public void execute(DSResponse dsResponse, Object o, DSRequest dsRequest) {
                final Record[] data = dsResponse.getData();
                if (data.length > 0) {
                    hasSessionToken = data[0].getAttributeAsBoolean("hasSessionToken");
                    authorizedByUser = data[0].getAttribute("authorizedByUser");
                    lastPublishDate = data[0].getAttributeAsDate("lastPublishDate");
                    lastPublishErrors = data[0].getAttribute("lastPublishErrors");
                    final String syncStatusStr = data[0].getAttribute("syncStatus");
                    syncStatus = syncStatusStr != null ? SyncStatus.valueOf(syncStatusStr) : null;
                } else {
                    hasSessionToken = false;
                    authorizedByUser = null;
                    lastPublishDate = null;
                    lastPublishErrors = null;
                    syncStatus = null;
                }
                updateListener.afterUpdate();
            }
        });
    }

    public boolean isAuthorized() {
        return hasSessionToken;
    }

    public String getAuthorizedByUser() {
        return authorizedByUser;
    }

    public Date getLastPublishDate() {
        return lastPublishDate;
    }

    public String getLastPublishErrors() {
        return lastPublishErrors;
    }

    public SyncStatus getSyncStatus() {
        return syncStatus;
    }

    public interface UpdateListener {
        void afterUpdate();
    }
}
